package loader

import (
	"bytes"
	"context"
	"fmt"
	"time"

	"github.com/spf13/viper"
	"go.etcd.io/etcd/clientv3"
)

func LoadConfigFromEtcd(key string) error {
	cli, err := clientv3.New(clientv3.Config{
		Endpoints: []string{"localhost:2379"},
	})
	if err != nil {
		return fmt.Errorf("failed to create etcd client: %w", err)
	}
	defer cli.Close()

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	resp, err := cli.Get(ctx, key)
	cancel()
	if err != nil {
		return fmt.Errorf("failed to get config from etcd: %w", err)
	}

	if len(resp.Kvs) == 0 {
		return fmt.Errorf("config key not found in etcd")
	}

	viper.SetConfigType("yaml")
	if err := viper.ReadConfig(bytes.NewBuffer(resp.Kvs[0].Value)); err != nil {
		return fmt.Errorf("failed to read config from etcd: %w", err)
	}

	return nil
}
